import base64
import pickle
from django_redis import get_redis_connection

def Merge_cookie_to_redis(user,request,response,cart_cookie):

    # 思路:
    # 1获取redis中的数据
    # 2遍历cookie数据
    # 3保存redis数据
    # 4清空cookie中的购物车数据

    cart_plain = pickle.loads(base64.b64decode(cart_cookie.encode()))  #{10:{'count':2,'selected':True}, 3:{'count':3,'selected':True}}

    redis = get_redis_connection('cart')

    cart_redis = {}
    cart_id_count = redis.hgetall('cart_%s'%user.id) #{b'3':b'1', b'16':b'3'}
    for id,count in cart_id_count.items():
        cart_redis[int(id)]= int(count)

    cart_selected_list = []
    for sku_id,sku_count_selected in cart_plain.items():
        cart_id_count[sku_id]=sku_count_selected['count']
        if sku_count_selected['selected']:
            cart_selected_list.append(sku_id)

    pl = redis.pipeline()
    pl.hmset('cart_%s'%user.id,cart_id_count)
    pl.sadd('cart_selected_%s'%user.id,*cart_selected_list)
    pl.execute()

    response.delete_cookie('cart')
    return response







